﻿var Time =
{
    getDaysInMonth: function(year, month) {
        return new Date(year, month + 1, 0).getDate();
    },
    getDaysPassed: function(startDate, endDate) {
        if (startDate == null || endDate == null || startDate > endDate)
            return 0;

        var oneDay = 1000 * 60 * 60 * 24;

        return Math.ceil((endDate - startDate) / oneDay);
    },
    getNoWeeks: function(year, month) {
        var noDays = getDaysInMonth(year, month);
        var firstWeek = new Date(year, month, 1, 0, 0, 0, 0).getWeekOfYear(1);
        var lastWeek = new Date(year, month, noDays, 0, 0, 0, 0).getWeekOfYear(1);
        return lastWeek - firstWeek + 1;
    },
    getMonthsPassed: function(startDate, endDate) {
        var m = Time.getYearsPassed(startDate, endDate) * 12;
        if (m > 0)
            return m + (11 - startDate.getMonth()) + endDate.getMonth() + 1;
        else return endDate.getMonth() - startDate.getMonth() + 1;
    },
    getYearsPassed: function(startDate, endDate) {
        return endDate.getYear() - startDate.getYear();
    },
    compareDays: function(date1, date2) {
        var d1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
        var d2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
        if (d1 < d2) return 0;
        if (d1 == d2) return 1;
        return 2;
    },
    dateToISO8601: function(dt) {
        var mnth = dt.getUTCMonth() + 1;
        if (mnth < 10) mnth = "0" + mnth;
        var day = dt.getUTCDate();
        if (day < 10) day = "0" + day;
        var yr = dt.getUTCFullYear();
        var hrs = dt.getUTCHours();
        if (hrs < 10) hrs = "0" + hrs;
        var min = dt.getUTCMinutes();
        if (min < 10) min = "0" + min;
        var secs = dt.getUTCSeconds();
        if (secs < 10) secs = "0" + secs;

        return yr + "-" + mnth + "-" + day + "T" + hrs + ":" + min + ":" + secs + "Z";
    },
    getTimeDifference: function(ds, de) {
        if (!ds || !de)
            return { H: 0, M: 0 };

        var m = (de.getHours() - ds.getHours()) * 60 + (de.getMinutes() - ds.getMinutes());
        var h = Math.floor(m / 60);
        m -= h * 60;
        return { H: h, M: m };
    }
};